package com.sunop.panticommon.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {
    /*
    * 创建一个名为problem.queue的队列，并持久化(给es写入数据)
     */
    @Bean
    public Queue problemQueue() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", "dead.letter.exchange"); // 死信交换器
        args.put("x-dead-letter-routing-key", "dead.letter.key");   // 死信路由键
        return new Queue("problem.queue", true, false, false, args); // 持久化队列
    }

    @Bean
    public DirectExchange problemExchange() {
        return new DirectExchange("problem.exchange", true, false); // 持久化交换器
    }

    @Bean
    public Binding problemBinding() {
        return BindingBuilder.bind(problemQueue())
                .to(problemExchange()).with("problem.key"); // 绑定队列与交换器
    }
    // problem.死信队列
    @Bean
    public Queue dlq() {
        return new Queue("problem.dlq", true);
    }

    @Bean
    public DirectExchange dlx() {
        return new DirectExchange("dead.letter.exchange");
    }

    @Bean
    public Binding dlqBinding() {
        return BindingBuilder.bind(dlq()).to(dlx()).with("dead.letter.key");
    }

    // email队列
    @Bean
    public Queue emailQueue() {
        return new Queue("email.queue", true);
    }

    @Bean
    public DirectExchange emailExchange() {
        return new DirectExchange("email.exchange");
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(emailQueue())
                .to(emailExchange())
                .with("email.routing.key");
    }

    // ==================== 动态班级队列配置 ====================

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }
    // ==================== 动态队列工厂方法 ====================

    /**
     * 创建班级交换机
     */
    public FanoutExchange createClassExchange(String classId) {
        return new FanoutExchange("class.exchange." + classId, true, false);
    }

    /**
     * 创建班级队列（带TTL和死信配置）
     */
    public Queue createClassQueue(String classId) {
        Map<String, Object> args = new HashMap<>();
        args.put("x-queue-mode", "lazy"); // 懒加载队列
        args.put("x-dead-letter-exchange", "dead.letter.exchange"); // 复用死信交换器
        args.put("x-dead-letter-routing-key", "dead.letter.key"); // 复用死信路由键
        return new Queue("class.queue." + classId, true, false, false, args);
    }

    /**
     * 绑定班级队列到交换机
     */
    public Binding bindClassQueueToExchange(String classId) {
        return BindingBuilder.bind(createClassQueue(classId))
                .to(createClassExchange(classId));
    }
}